package com.yami.shop.mystery.common.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.model.User;
import com.yami.shop.common.bean.PageDTO;
import com.yami.shop.common.bean.PageVO;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.common.util.PageUtil;
import com.yami.shop.common.util.PoiExcelUtil;
import com.yami.shop.dao.UserMapper;
import com.yami.shop.mystery.common.dao.ActivityWhiteListMapper;
import com.yami.shop.mystery.common.dao.ActivityWhiteMapper;
import com.yami.shop.mystery.common.dto.ActivityWhiteDto;
import com.yami.shop.mystery.common.dto.WhiteUserDto;
import com.yami.shop.mystery.common.model.ActivityWhite;
import com.yami.shop.mystery.common.model.ActivityWhiteList;
import com.yami.shop.mystery.common.service.ActivityWhiteListService;
import com.yami.shop.mystery.common.service.ActivityWhiteService;
import com.yami.shop.mystery.common.vo.ActivityWhiteExcle;
import com.yami.shop.security.common.util.AuthUserContext;
import lombok.AllArgsConstructor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 白名单业务实现类
 *
 * @author wxf
 * @date 2023/4/4 9:35
 */
@Service
@AllArgsConstructor
public class ActivityWhiteServiceImpl extends ServiceImpl<ActivityWhiteMapper, ActivityWhite> implements ActivityWhiteService {

    private final ActivityWhiteMapper activityWhiteMapper;

    private final ActivityWhiteListMapper activityWhiteListMapper;

    private final UserMapper userMapper;

    private final ActivityWhiteListService activityWhiteListService;

    @Override
    public IPage<ActivityWhiteDto> getList(PageParam<ActivityWhiteDto> page, String activityName) {
        IPage<ActivityWhiteDto> pageWhite = activityWhiteMapper.getList(page, AuthUserContext.get().getShopId(), activityName);
        return pageWhite;
    }

    @Override
    public Long saveByList(List<ActivityWhiteExcle> whiteExcles, Long activityId) {

        // 通过手机号去空，去重
        List<String> list = whiteExcles.stream().filter(s -> ObjectUtil.isNotEmpty(s.getPhone())).map(s -> s.getPhone()).distinct().collect(Collectors.toList());
        if (list.size() < whiteExcles.size()) {
            throw new YamiShopBindException("手机号重复");
        }

        long batchNo = System.currentTimeMillis();
        // 获取白名单主表
        ActivityWhite activityWhite = activityWhiteMapper.selectOne(new QueryWrapper<ActivityWhite>().eq("activity_id", activityId));
        if (ObjectUtil.isEmpty(activityWhite)) { // 新增
            activityWhite = new ActivityWhite();
            activityWhite.setActivityId(activityId);
            activityWhite.setWhiteNum(list.size());
            activityWhite.setBatchNo(batchNo + "");
            activityWhite.setShopId(AuthUserContext.get().getShopId());
            activityWhiteMapper.insert(activityWhite);
        } else {
            // 已存在增量更新，已存在的不再更新，新增的更新
            //过滤重复的用户
            List<ActivityWhiteList> activityWhiteLists = activityWhiteListMapper.selectList(new QueryWrapper<ActivityWhiteList>().eq("white_id", activityWhite.getId()));
            List<String> whitePhone = activityWhiteLists.stream().map(s -> s.getUserPhone()).collect(Collectors.toList());
            list = list.stream().filter(s -> !whitePhone.contains(s)).collect(Collectors.toList());
            // 修改主表白名单人数
            activityWhiteMapper.updateWhiteNum(activityWhite.getId(), list.size());
        }

        List<User> addWhiteList = new ArrayList<>();
        //数据拆分
        List<List<String>> phonesSplits = ListUtil.split(list, 100);
        for (List<String> phones : phonesSplits) {
            addWhiteList.addAll(userMapper.listByUserPhones(phones));
        }

        //保存数据
        List<ActivityWhiteList> addData = new ArrayList<>();

        for (User addWhite : addWhiteList) {
            ActivityWhiteList activityWhiteList = new ActivityWhiteList();
            activityWhiteList.setBatchNo(batchNo + "");
            activityWhiteList.setWhiteId(activityWhite.getId());
            activityWhiteList.setUserId(addWhite.getUserId());
            activityWhiteList.setUserPhone(addWhite.getUserMobile());
            //获取限购数
            ActivityWhiteExcle activityWhiteExcle = whiteExcles.stream().filter(s -> ObjectUtil.isNotEmpty(s.getPhone())).filter(s -> s.getPhone().equals(addWhite.getUserMobile())).collect(Collectors.toList()).get(0);
            activityWhiteList.setPurchaseNum(activityWhiteExcle.getPurchaseNum());
            activityWhiteList.setDiscountsNum(activityWhiteExcle.getDiscountsNum());
            activityWhiteList.setPublicNum(activityWhiteExcle.getPublicNum());
            addData.add(activityWhiteList);
        }
        activityWhiteListService.saveBatch(addData);
        return Long.parseLong(addData.size() + "");
    }

    @Override
    public IPage<WhiteUserDto> getWhiteUserList(PageParam<ActivityWhiteDto> pageVo, Long whiteId, String phone) {
        IPage<WhiteUserDto> page = activityWhiteListMapper.getWhiteUserList(pageVo,whiteId, phone);
        return page;
    }

    @Override
    public Boolean updateStatus(String id, String status) {
        return activityWhiteListMapper.updateStatus(id, status) > 0 ? true : false;
    }

    @Override
    public void exportModel(HttpServletResponse response, String[] headerNames, String fileName) {
        //通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getBigWriter();
        // 商品导出or模板
        List<String> headerList = Arrays.asList(headerNames);
        Sheet sheet = writer.getSheet();
        for(int i = 0 ; i< headerList.size();i++){
            sheet.setColumnWidth(i, 20 * 256);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if(ObjectUtil.isNotEmpty(fileName)){
            writer.merge(headerList.size() - 1, fileName + "-" + sdf.format(new Date()));
        }
        writer.writeRow(headerList);
        try (Workbook workbook = writer.getWorkbook()) {
            CellStyle cellStyle = workbook.createCellStyle();
            DataFormat format = workbook.createDataFormat();
            cellStyle.setDataFormat(format.getFormat("@"));
            sheet.setDefaultColumnStyle(5, cellStyle);
            PoiExcelUtil.writeExcel(response, writer);
        } catch (Exception e) {
            log.error("Exception:", e);
        }
    }
}
